package factory

import (
	"github.com/goccy/go-json"
	"github.com/nats-io/nats.go"
)

type NatConf struct {
	Urls     string `yaml:"url"`
	User     string `yaml:"user"`
	Password string `yaml:"passwd"`
}

type NatClient struct {
	Conn *nats.Conn
}

func (nc *NatConf) Connected() (*NatClient, error) {
	con, er := nats.Connect(nc.Urls, nats.UserInfo(nc.User, nc.Password))
	if er != nil {
		return nil, er
	}
	return &NatClient{Conn: con}, nil
}

func (nc *NatClient) Close() {
	nc.Conn.Drain()
	nc.Conn.Close()
}

func (nc *NatClient) ReplyData(data interface{}, reply string) error {
	res, _ := json.Marshal(data)
	return nc.Conn.Publish(reply, res)
}
